<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { computed, ref } from 'vue'
import { ElTable, ElMessage } from 'element-plus'
import {deviceList, deviceHot} from '@/api/device'
import {groupList} from '@/api/group'
import groupSelect from '@/components/GroupSelect.vue'

const inputKey = ref('')
const pageTotal = ref(1)
const props = {
  multiple: true,
}
//分组请求参数
const page = ref(1)
const size = ref(10)
const indexMethod = (index: number) => {
  return index + 1
}
interface Device {
  groupName: string
  name: string
  deviceId: string
  state: string
  working: string
  temperature: number
  humidity: number
  time: string
}
//选择设备
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Device[]>([])
const handleSelectionChange = (val: Device[]) => {
  // console.log(val)
  multipleSelection.value = val
}

//请求参数
const paramsDevice = ref({
  page: 1,
  size: 10,
  groupId: "",
  name: ""
})
const paramsHot = ref({
  temperature: 1,
  action: "ON",
  deviceIds: []
})

const tableData= ref<Device[]>([])
//获取设备信息
const getDevice = async() => {
  const now = new Date().getTime()
  let res = await deviceList(paramsDevice.value.page, paramsDevice.value.size,paramsDevice.value.name)
  pageTotal.value = res.data.total
  tableData.value = res.data.list.map((item: { group: { name: any; }; name: any; deviceId: any; malfunction: any; working: any; temperature: any; humidity: any; time: any;}) => ({
    groupName: item.group.name,
    name: item.name,
    deviceId: item.deviceId,
    state: item.malfunction ? '异常':'正常',
    working: item.working ? '是' : '否',
    temperature: item.temperature,
    humidity: item.humidity,
    time: ((now - new Date(item.time).getTime()) / (1000 * 60)).toFixed(2)
  }))
  // console.log(tableData.value)
}
getDevice()

const getColor = (row: Device) => {
  return row.working.includes('是') ? 'red' : '';
}
const getColor2 = (row: Device) => {
  return row.state.includes('异常') ? 'red' : '';
}
//获取分组设备
const groups = ref()
const getGroup = async() => {
  let res2 = await groupList(page.value,size.value,'')
  // console.log(res2.data.list)
  groups.value = res2.data.list.map((item:any) => ({
    value: item.defaultTemperature,
    label: item.name,
    children: item.devices.map((e:any) => ({
      value: e.id,
      label: e.name
    }))
  }))
  // console.log(groups.value)
}
getGroup()
//选择设备
const objGroup = ref()
const changeDevice = (value: any) => {
  let obj:any = {}
  value.forEach((item: any) => {
      let first = item[0]
      if(! obj[first]){
        obj[first] = [item[1]]
      }else{
        obj[first].push(item[1])
      }
  })
  objGroup.value = obj
}
//开始加热
const startHot = async() => {
  paramsHot.value.action = "ON"
  for(let key in objGroup.value){
    console.log(key, objGroup.value[key])
    paramsHot.value.temperature = parseInt(key)
    paramsHot.value.deviceIds = objGroup.value[key]
    let res:any = await deviceHot(paramsHot.value)
    if(res.code == 200){
      ElMessage({
        message: '加热成功',
        type: 'success',
        plain: true,
      })
    }
  }
}
//停止加热
const stopHot = async() => {
  paramsHot.value.action = "OFF"
  for(let key in objGroup.value){
    console.log(key, objGroup.value[key])
    paramsHot.value.temperature = parseInt(key)
    paramsHot.value.deviceIds = objGroup.value[key]
    let res:any = await deviceHot(paramsHot.value)
    if(res.code == 200){
      ElMessage({
        message: '成功停止',
        type: 'error',
        plain: true,
      })
    }
  }
}

//搜索
const searchBtn = () =>{
  paramsDevice.value.name = inputKey.value
  getDevice()
}

//页大小
const handleSizeChange = (val: number) => {
  paramsDevice.value.size = val
  getDevice()
}
const handleCurrentChange = (val: number) => {
  // devicePage.value = val
  paramsDevice.value.page = val
  getDevice()
}
</script>
<template>
  <el-form inline>
    <el-form-item>
      <el-input
        v-model="inputKey"
        style="max-width: 300px"
        placeholder="输入搜索关键词"
      >
        <template #append>
          <el-button :icon="Search" @click="searchBtn"/>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-cascader
        placeholder="请选择设备"
        :options="groups"
        :props="props"
        filterable
        clearable
        @change="changeDevice"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" round class="btn" @click="startHot">开始加热</el-button>
      <el-button type="primary" round class="btn" @click="stopHot">停止加热</el-button>
    </el-form-item>
  </el-form>
  <div class="table">
    <el-table
    ref="multipleTableRef"
    :data="tableData"
    style="width: 90%"
    border
    @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" :index="indexMethod" width="80" />
      <el-table-column property="groupName" label="设备分组" width="120"></el-table-column>
      <el-table-column property="name" label="设备名称" width="120" />
      <el-table-column property="deviceId" label="设备ID" width="120"/>
      <el-table-column property="state" label="设备状态" width="120">
        <template #default="{ row }">
          <span :style="{ color: getColor2(row) }">{{ row.state }}</span>
        </template>
      </el-table-column>
      <el-table-column property="working" label="正在工作" width="120"><!-- 使用内联样式绑定 -->
        <template #default="{ row }">
          <span :style="{ color: getColor(row) }">{{ row.working }}</span>
        </template>
      </el-table-column>
      <el-table-column property="temperature" label="当前温度（℃）" width="140" />
      <el-table-column property="humidity" label="当前湿度（%H）" width="140" />
      <el-table-column property="time" label="已加热时间（min）" />
    </el-table>
  </div>
  <div class="foot">
    <el-pagination
      v-model:current-page="paramsDevice.page"
      v-model:page-size="paramsDevice.size"
      :page-sizes="[10, 50, 100, 150]"
      layout="sizes, prev, pager, next, jumper"
      :total="pageTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
  
</template>
<style scoped>
.btn{
  width: 100px;
  margin-left: 40px;
}
.table{
  margin-top:30px
}
.foot{
  display: flex;
  margin-top: 40px;
  justify-content: center;
}

</style>
